<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 康复处方
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.prePtNm" placeholder="姓名" class="handle-input mr10" @keyup.enter.native="handleSearch"></el-input>
                <el-input v-model="query.preCrtBy" placeholder="创建人" class="handle-input mr10" @keyup.enter.native="handleSearch"></el-input>
                <el-input v-model="query.preTherape" placeholder="治疗师" class="handle-input mr10" @keyup.enter.native="handleSearch"></el-input>
                <el-select v-model="query.preState" placeholder="训练状态" class="handle-select mr10" @keyup.enter.native="handleSearch">
                    <el-option key="00" label="未使用" value="00"></el-option>
                    <el-option key="01" label="已使用" value="01"></el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="el-button" icon="el-icon-delete" @click="handleReset">重置</el-button>
            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column prop="ptId" label="患者ID" width="200" align="center"></el-table-column>
                <el-table-column prop="preId" label="处方ID" width="200" align="center"></el-table-column>
                <el-table-column prop="prePtNm" label="姓名" align="center"></el-table-column>
                <el-table-column prop="prePtAge" label="年龄" align="center"></el-table-column>
                <el-table-column prop="prePtSexText" label="性别" align="center"></el-table-column>
                <el-table-column prop="preCrtBy" label="创建人" align="center"></el-table-column>
                <el-table-column label="训练时长/分钟" width="150" align="center">
                    <template slot-scope="scope">{{scope.row.preDuration/60}}</template>
                </el-table-column>
<!--                <el-table-column prop="preDuration" label="" align="center" ></el-table-column>-->
                <el-table-column prop="preStateText" label="训练状态" align="center"></el-table-column>
                <el-table-column prop="preIstTm" label="创建时间" width="180" align="center"></el-table-column>
                <el-table-column prop="preTherape" label="治疗师" align="center"></el-table-column>
                <el-table-column label="操作" width="280" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-thumb"
                                @click="handlePrescription(scope.$index, scope.row)"
                        >查看处方</el-button>
                        <el-button v-if="roleIds !=='system'"
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑处方</el-button>
                        <el-button v-if="roleIds !=='system'"
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageIndex"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>
        <!-- 编辑弹出框 -->
        <el-dialog title="编辑处方" :visible.sync="editVisible" width="30%" :before-close="editColse">
            <div style="margin-bottom: 10px;">
                <el-form ref="editForm" :rules="editFormRules" :model="editForm" label-width="80px">
                    <el-row style="margin-top: 10px">
                        <el-col :span="2" style="margin-left: 15px">
                            <el-button style="background-color: #c2e7b0"
                                       @click="addTab(tabLength)"
                            >
                                +
                            </el-button>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="治疗师" prop="preCrtBy">
                                <el-select v-model="editForm.preCrtBy" change="change">
                                    <el-option  v-for="crtBy in crtBys" :label="crtBy.userNm+'('+crtBy.userAcct+')'" :key="crtBy.userAcct" :value="crtBy.userAcct"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="训练次数" prop="preTimes" >
                                <el-input type="number" v-model="editForm.preTimes" :min="1" @keyup.native="proving1"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <el-tabs v-model="editcfableTabsValue" type="card" closable @tab-remove="removeTab">
                <el-tab-pane v-if="editcfableTabs && editcfableTabs.length >=0"
                             v-for="(item, index) in editcfableTabs"
                             :key="item.name"
                             :label="item.title"
                             :name="item.name">
                    <component :is="item.content" v-on:formData="handleFormData" :name="item.name" v-bind:contentForm="item.contentForm"></component>
                </el-tab-pane>
            </el-tabs>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editColse">关 闭</el-button>
                <el-button type="primary" @click="saveEdit">提 交</el-button>
            </span>
        </el-dialog>
        <!-- 查看处方弹出框 -->
        <el-dialog title="查看处方" :visible.sync="prescriptionVisible" width="30%" :before-close="seeColse">
            <div style="margin-bottom: 10px;">
                <el-form  label-width="80px">
                    <el-row style="margin-top: 10px">
                        <el-col :span="2" style="margin-left: 15px">
<!--                            <el-button style="background-color: #c2e7b0"-->
<!--                                       @click="addTab(editableTabsValue)"-->
<!--                            >-->
<!--                                +-->
<!--                            </el-button>-->
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="治疗师" >
                                    <el-input readonly  v-model="preCrtBy"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="训练次数">
                                <el-input readonly type="number" v-model="preTimes"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <el-tabs v-model="editableTabsValue" type="card">
                <el-tab-pane v-if="editableTabs && editableTabs.length >=0"
                             v-for="(item, index) in editableTabs"
                             :key="item.name"
                             :label="item.title"
                             :name="item.name">
                    <component :is="item.content"  v-bind:contentForm="item.contentForm"></component>
                </el-tab-pane>
            </el-tabs>
            <span slot="footer" class="dialog-footer">
                                <el-button @click="seeColse">关 闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import presModel from '../prescription/presModel'
    import editModel from "./editModel";
    import { getPrescriptions,doDelete,selectBypreId,doUpdate} from '../../../api/prescription/prescription';
    import {getcrtBys} from "../../../api/system/user/user";
    export default {
        name: 'role',
        data() {
            return {
                query: {
                    prePtNm: '',
                    preCrtBy: '',
                    preTherape:'',
                    preState:'',
                    userAcct:localStorage.getItem('ms_userAcct'),
                    pageIndex: 1,
                    pageSize: 10
                },
                userAcct: localStorage.getItem('ms_userAcct'),
                tableData: [],
                multipleSelection: [],
                editVisible: false,
                prescriptionVisible:false,
                pageTotal: 0,
                editForm: {},
                editTables:[],
                idx: -1,
                id: -1,
                crtBys:[],
                namess:[],
                editableTabsValue: '1',
                editableTabs: [],
                tabIndex: 1,
                editcfableTabsValue: '1',
                editcfableTabs: [],
                edittabIndex: 1,
                preCrtBy:'',//治疗师
                preTimes:0,//次数
                ptId:'',//当前操作患者
                preId:'',//当前操作处方ID
                tabLength:'',
                roleIds:localStorage.getItem('ms_roleIds'),
                editFormRules:{
                    preCrtBy: [
                        { required: true, message: '请选择治疗师', trigger: 'blur' },
                    ],
                    preTimes: [
                        { required: true, message: '请输入训练次数', trigger: 'blur' },
                    ],
                },
            };
        },
        created() {
            this.getData();
        },
        components:{
            presModel,
            editModel
        },
        methods: {
            // 获取后台数据
            getData() {
                getPrescriptions(this.query).then(res => {
                    if (res.success === true){
                        this.tableData = res.data;
                        this.pageTotal = res.total;
                    } else {
                        this.$message.error("查询失败！");
                        this.tableData = [];
                        this.pageTotal = 0;
                    }
                });
            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageIndex', 1);
                this.getData();
            },
            // 触发重置按钮
            handleReset() {
                this.query.prePtNm = "";
                this.query.preCrtBy = "";
                this.query.preTherape = "";
                this.query.preState="";
                this.getData();
            },
            // 删除操作
            handleDelete(index, row) {
                if (row.preState!="00"){
                    this.$message.error("该处方已开始使用,无法删除");
                    return;
                }
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    //后台进行删除操作
                    doDelete({preId:row.preId}).then(res => {
                        if (res.data==1){
                            this.$message.success('删除成功');
                            this.getData();
                        } else {
                            this.$message.error('删除失败');
                            this.getData();
                        }
                    });
                })
                    .catch(() => {
                        this.$message({
                            message:'已取消删除'
                        });
                    });
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 编辑操作
            async handleEdit(index, row) {
                if (row.preState!="00"){
                    this.$message.error("该处方已开始使用,无法编辑");
                    return;
                }
                this.editcfableTabs=[];
                this.edittabIndex=1;
                this.editcfableTabsValue='1';
                this.ptId=row.ptId;
                this.preId=row.preId;
                //获取所有治疗师
                await getcrtBys().then(res =>{
                    this.crtBys = res.data;
                    //根据处方id查询处方记录
                     selectBypreId({preId: row.preId}).then(res => {
                         if (res.success==true){
                             for(let i=0;i<res.data.standPrescriptionActionPOJOS.length;i++){
                                 res.data.standPrescriptionActionPOJOS[i].preActionTime=res.data.standPrescriptionActionPOJOS[i].preActionTime/60;
                                 this.editcfableTabs.push({
                                     title: '训练类型选择',
                                     name: res.data.standPrescriptionActionPOJOS[i].preActionSort,
                                     content:'editModel',
                                     contentForm:res.data.standPrescriptionActionPOJOS[i]
                                 });
                             };
                             this.tabLength=res.data.standPrescriptionActionPOJOS.length;
                             const obj={preCrtBy:res.data.preTherape,preTimes:parseInt(res.data.preTimes)}
                             this.editForm=obj;
                             this.editVisible = true;
                         }else {
                             this.$message.error('处方查询失败');
                         }
                    });
                });
            },
            // 保存编辑
            saveEdit() {
                if (this.editcfableTabs.length==0){
                    this.$message.error('请至少保存一个处方记录');
                    return;
                }
                console.log("json",{"json":JSON.stringify({"standPrescriptionActionPOJOS":this.editTables,"preTherape":this.editForm.preCrtBy,"preTimes":this.editForm.preTimes,"ptId":this.ptId,"preId":this.preId,"preUpdBy":localStorage.getItem('ms_userAcct')})});
                if (this.editForm.preTimes==undefined || this.editForm.preTimes==null || this.editForm.preTimes=="" || this.editForm.preTimes=="0"){
                    this.$message.error('请正确输入训练次数');
                    return;
                }
                //判断第几个页签是未保存的
                let returnStr="";
                for (let i=0;i<this.editcfableTabs.length;i++){
                    //查找是否有保存的
                    if (this.editTables.length!==0){
                        for (let j=0;j<this.editTables.length;j++){
                            if (this.editcfableTabs[i].name==this.editTables[j].name){
                                break;
                            }
                            if (j==this.editTables.length-1 && this.editcfableTabs[i].name !==this.editTables[j].name){
                                returnStr=returnStr+(i+1)+',';
                            }
                        }
                    }else {
                        returnStr=returnStr+(i+1)+',';
                    }
                }
                if (returnStr!==""){
                    returnStr=returnStr.substring(0,returnStr.length-1);
                    this.$message.error("标签页："+returnStr+"未保存，请保存");
                    return;
                }
                doUpdate({"json":JSON.stringify({"standPrescriptionActionPOJOS":this.editTables,"preTherape":this.editForm.preCrtBy,"preTimes":this.editForm.preTimes,"ptId":this.ptId,"preId":this.preId,"preUpdBy":localStorage.getItem('ms_userAcct')})}).then(res => {
                    if (res.data == 1) {
                        this.editVisible = false;
                        this.editForm = {};
                        this.editTables=[];
                        this.getData();
                        this.$message.success('编辑成功');
                    } else {
                        this.$message.error('编辑失败');
                    }
                });
            },
            editColse(){//关闭编辑按钮
                this.$confirm('确认关闭？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        this.editVisible = false;
                        this.editForm = {};
                        this.editTables=[];
                        this.getData();
                    })
                    .catch(() => {
                        this.$message({
                            message:'已取消操作'
                        });
                    });
            },
            change(){
                debugger;
            },
            /*表单重置*/
            resetForm(refname){
                if (this.$refs[refname] !== undefined){
                    this.$refs[refname].resetFields();
                }
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageIndex', val);
                this.getData();
            },
            //查看弹出框
            handlePrescription(index, row) {
                this.editableTabs=[];
                this.tabIndex=1;
                this.editableTabsValue='1';
                //根据处方id查询处方记录
                selectBypreId({preId: row.preId}).then(res => {
                    if (res.success==true) {
                        for (let i = 0; i < res.data.standPrescriptionActionPOJOS.length; i++) {
                            res.data.standPrescriptionActionPOJOS[i].preActionTime = res.data.standPrescriptionActionPOJOS[i].preActionTime / 60;
                            this.editableTabs.push({
                                title: '训练类型选择',
                                name: res.data.standPrescriptionActionPOJOS[i].preActionSort,
                                content: 'presModel',
                                contentForm: res.data.standPrescriptionActionPOJOS[i]
                            });
                        }
                        this.preCrtBy = res.data.preTherape;
                        this.preTimes = parseInt(res.data.preTimes);
                        this.prescriptionVisible = true;
                    }else{
                        this.$message.error('处方查询失败');
                    }
                })
            },
            seeColse(){
                this.$confirm('确认关闭？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        this.prescriptionVisible = false;
                    })
                    .catch(() => {
                        this.$message({
                            message:'已取消操作'
                        });
                    });

            },
            addTab(targetName) {
                this.edittabIndex=targetName;
                targetName=targetName+'';
                //每个tab的内容
                let newTabName = ++this.edittabIndex + '';
                this.editcfableTabs.push({
                    title: '训练类型选择',
                    name: newTabName,
                    content:'editModel',
                    contentForm:{
                        preActionType:'00',
                        preActionElectricalStatus:'00'
                    }
                });
                this.editcfableTabsValue = newTabName;
                this.tabLength=++targetName;
            },
            removeTab(targetName) {
                let tabs = this.editcfableTabs;
                targetName=targetName+'';
                let activeName = this.editcfableTabsValue;
                if (activeName === targetName) {
                    tabs.forEach((tab, index) => {
                        if (tab.name === targetName) {
                            let nextTab = tabs[index + 1] || tabs[index - 1];
                            if (nextTab) {
                                activeName = nextTab.name;
                            }
                        }
                    });
                }
                this.editcfableTabsValue = activeName;
                this.editcfableTabs = tabs.filter(tab => tab.name !== targetName);
                let removeRes=[];
                for (let i=0;i<this.editTables.length;i++){
                    if (this.editTables[i].name !==targetName+''){
                        removeRes.push(this.editTables[i]);
                    }
                };
                this.editTables=removeRes;
            },
            // 处理子组件传递数据
            handleFormData:function (somedata) {
                somedata.preActionTime=somedata.preActionTime *60;
                console.log("somedata----",somedata);
                let modelFms=this.editTables;
                const names=this.namess;
                if (modelFms.length!==0){
                    if (names.indexOf(somedata.name)==-1){//不存在
                        names.push(somedata.name);
                        modelFms.push(somedata);
                    }else{//已存在
                        modelFms = modelFms.filter(item => {
                            return item.name != somedata.name;
                        });
                        modelFms.push(somedata);
                    }
                }else{
                    names.push(somedata.name);
                    modelFms.push(somedata);
                };
                this.namess=names;
                //进行排序
                for (let i = 0; i <modelFms.length; i++) {
                    for(let j=0;j<modelFms.length-i-1;j++){
                        if(modelFms[j].name>modelFms[j+1].name){
                            let temp=modelFms[j];
                            modelFms[j]=modelFms[j+1];
                            modelFms[j+1]=temp;
                        }
                    }
                };
                this.editTables = modelFms;
            },
            proving1(e) {
                var keynum = window.event ? e.keyCode : e.which;   //获取键盘码
                var keychar = String.fromCharCode(keynum);  //获取键盘码对应的字符
                if (keynum ==189|| keynum==190||keynum == 109 || keynum == 110) {
                    this.$message.warning('禁止输入小数以及负数');
                    e.target.value = ' ';
                    return
                }
                if (keynum==69){
                    this.$message.warning('禁止输入e或E');
                    e.target.value = ' ';
                    return;
                }
            },
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .table {
        width: 100%;
        font-size: 14px;
    }
    .red {
        color: #ff0000;
    }
    .mr10 {
        margin-right: 10px;
    }

</style>
